const column = require('../models/column');
const article = require('../models/article');
const { add, page, list, info, update, del } = require('./utils');

let addData = (body, res) => {
	add(article, body, res);
};
let getList = (body, res) => {
	list(article, body, res);
};
let getInfo = (body, res) => {
	info(article, body, res);
};
let updateData = (body, res) => {
	update(article, body, res);
};
let deleteData = (body, res) => {
	del(article, body, res);
};
let updateViews = async (body, res) => {
	let num = -1;
	await article
		.findOne({
			where: { id: body.id },
			raw: true
		})
		.then(result => {
			num = result.views;
		});
	body.views = num + 1;
	await article
		.update(body, {
			where: { id: body.id }
		})
		.then(result => {
			res.json({
				code: 0,
				data: null,
				msg: 'success'
			});
		})
		.catch(err => {
			res.json({
				code: 500,
				data: null,
				msg: err
			});
		});
};
module.exports = {
	addData,
	getPage: async (body, res) => {
		let currentPage = parseInt(body.currentPage);
		let pageSize = parseInt(body.pageSize);
		let where = {};
		let arr = ['title'];
		for (let i in body) {
			arr.forEach(item => {
				if (body[i] !== '' && i === item) {
					where[i] = body[i];
				}
			});
		}
        console.log(body)
        let order = []
        if(body.sort && body.order) {
            order = [[body.sort, body.order]];
        }
        console.log(order)
		await article
			.findAndCountAll({
				where: where,
				offset: (currentPage - 1) * pageSize,
				limit: pageSize,
				order: order
			})
			.then(async result => {
				let arr = result.rows;
				for (let i = 0; i < arr.length; i++) {
					await column
						.findOne({
							where: { id: arr[i].cid },
							raw: true
						})
						.then(result => {
							arr[i]['dataValues']['cname'] = result.name;
						});
				}
				res.json({
					code: 0,
					data: {
						currPage: parseInt(body.currentPage),
						list: arr,
						pageSize: parseInt(body.pageSize),
						totalCount: result.count,
						totalPage: Math.ceil(
							result.count / parseInt(body.pageSize)
						)
					},
					msg: 'success'
				});
			});
	},
	getList,
	getInfo,
	updateData,
	deleteData,
	updateViews
};
